import {
  reqGetCode,
  reqUserRegister,
  reqUserLogin,
  reqGetUserInfo,
  reqLogout,
} from "@/api";
import { setToken, getToken, removeToken } from "@/utils/token";
const state = {
  code: '',
  // token: localStorage.getItem('TOKEN'),
  token: getToken(),
  userInfo: {},
};
const actions = {
  // 获取验证码
  async getCode({ commit }, phone) {
    let result = await reqGetCode(phone)
    // console.log(result)
    if (result.code == 200) {
      commit('GETCODE', result.data);
      return 'ok'
    } else {
      return Promise.reject(new Error('failed!!'))
    }
  },
  //   用户注册
  async userRegister({ commit }, user) {
    // console.log('user', user)
    let result = await reqUserRegister(user);
    // console.log('result', result)
    if (result.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('failed!!'))
    }
  },
  // 用户登录
  async userLogin({ commit }, data) {
    let result = await reqUserLogin(data);
    // console.log(result)
    // 服务器下发token，用户唯一标志符（eg：uuid）
    // 将来经常通过带token找服务器要用户信息，进行展示
    if (result.code == 200) {
      commit('USERLOGIN', result.data.token);
      // 持久化存储token
      // localStorage.setItem('TOKEN', result.data.token);
      setToken(result.data.token)
      return 'ok'
    } else {
      return Promise.reject(new Error('failed!!!'))
    }
  },
  // 获取用户信息
  async getUserInfo({ commit }) {
    let result = await reqGetUserInfo();
    // console.log(result)
    if (result.code == 200) {
      commit('GETUSERINFO', result.data)
      return 'ok'
    } else {
      return Promise.reject(new Error('failed!!!'))
    }
  },
  // 用户退出登录
  async userLogout({ commit }) {
    // 只是向服务器发送一次 退出请求
    let result = await reqLogout();

    if (result.code == 200) {
      commit('CLEARUSER');
      return 'ok'
    } else {
      return Promise.reject(new Error('failed!!'))
    }
  },

};
const mutations = {
  GETCODE(state, code) {
    state.code = code;
  },
  USERLOGIN(state, token) {
    state.token = token
  },
  GETUSERINFO(state, userInfo) {
    state.userInfo = userInfo || {}
  },
  CLEARUSER(state) {
    state.token = '',
    state.userInfo = {};
    removeToken(); // 清空本地存储
  },
};
const getters = {};

export default {
  state,
  actions,
  mutations,
  getters,
}
